package com.bhajanswarupa.paginationutils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.Query;

public class JpaPage<T> extends PageImpl<T> implements Page<T> {

	private static final long serialVersionUID = 1670549701278741672L;

    private static final Logger LOGGER = LoggerFactory.getLogger(JpaPage.class);


	/**
	 * Construct a new Page. Page numbers are zero-based, so the first page is
	 * page 0.
	 * 
	 * @param query
	 *            the Hibernate Query
	 * @param pageNumber
	 *            the page number (zero-based)
	 * @param pageSize
	 *            the number of results to display on the page
	 */
	@SuppressWarnings("unchecked")
	public JpaPage(Query query, int pageNumber, int pageSize) {

		this.pageNumber = pageNumber;
		this.pageSize = pageSize;
		totalResults = query.getResultList().size();
		/*
		 * We set the max results to one more than the specified pageSize to
		 * determine if any more results exist (i.e. if there is a next page to
		 * display). The result set is trimmed down to just the pageSize before
		 * being displayed later (in getList()).
		 */
		results = query.setFirstResult(pageNumber * pageSize).setMaxResults(
				pageSize + 1).getResultList();
		results.size();

		// set totalNumberOfElements
	}


	/**
	 * Construct a new Page. Page numbers are zero-based, so the first page is
	 * page 0.
	 * 
	 * @param query
	 *            the Hibernate Query
	 */
	@SuppressWarnings("unchecked")
	public JpaPage(Query query) {

		LOGGER.debug(query.toString());
		pageNumber = 0;
		pageSize = PAGESIZE_ALLRESULTS;
		results = query.getResultList();
		totalResults = results.size();
		LOGGER.debug("totalResults = " + totalResults);
	}

}
